package cn.dreamtobe.percentsmoothhandler.demo;

import cn.dreamtobe.percentsmoothhandler.ISmoothTarget;
import cn.dreamtobe.percentsmoothhandler.SmoothHandler;
import ohos.agp.components.AttrSet;
import ohos.agp.components.ProgressBar;
import ohos.app.Context;

import java.lang.ref.WeakReference;

public class SmoothProgressBar extends ProgressBar implements ISmoothTarget {
    public SmoothProgressBar(Context context) {
        super(context);
    }

    public SmoothProgressBar(Context context, AttrSet attrSet) {
        super(context, attrSet);
    }

    public SmoothProgressBar(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
    }
    @Override
    public float getPercent() {
        return getProgress() / (float) getMax();
    }

    @Override
    public void setPercent(float percent) {
        setProgressValue((int) Math.ceil(percent * getMax()));
    }

    @Override
    public void setProgressValue(int progress) {
        if (smoothHandler != null) {
            smoothHandler.commitPercent(progress / (float) getMax());
        }
        super.setProgressValue(progress);
    }

    private SmoothHandler smoothHandler;

    @Override
    public void setSmoothPercent(float percent) {
        getSmoothHandler().loopSmooth(percent);
    }

    @Override
    public void setSmoothPercent(float percent, long durationMillis) {
        getSmoothHandler().loopSmooth(percent, durationMillis);
    }
    private SmoothHandler getSmoothHandler() {
        if (smoothHandler == null) {
            smoothHandler = new SmoothHandler(new WeakReference<ISmoothTarget>(this));
        }
        return smoothHandler;
    }
}
